package pay

import (
	"context"
	"strconv"
	"time"

	"github.com/agui-coder/simple-admin-pay-rpc/internal/logic/order"
	"github.com/agui-coder/simple-admin-pay-rpc/internal/svc"
	"github.com/agui-coder/simple-admin-pay-rpc/types/pay"
	"github.com/agui-coder/simple-admin-pay-rpc/utils/errorhandler"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreatePancakebotOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreatePancakebotOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePancakebotOrderLogic {
	return &CreatePancakebotOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// CreatePancakebotOrder PancakebotOrder management
func (l *CreatePancakebotOrderLogic) CreatePancakebotOrder(in *pay.PancakebotOrderInfo) (*pay.BaseIDResp, error) {

	pancakeOrder, err := l.svcCtx.DB.PancakebotOrder.Create().SetUserID(*in.UserId).
		SetComboID(*in.ComboId).
		SetComboName(*in.ComboName).
		SetComboIngredient(*in.ComboIngredient).
		SetDeviceID(*in.DeviceId).
		SetPrice(*in.Price).
		SetDeviceID(*in.DeviceId).
		SetPayStatus(false).
		SetRefundPrice(0).Save(l.ctx)
	if err != nil {
		return nil, errorhandler.DefaultEntError(l.Logger, err, in)
	}
	payOrder, err := order.NewCreateOrderLogic(l.ctx, l.svcCtx).CreateOrder(&pay.OrderCreateReq{
		UserIp:          "",
		Subject:         *in.ComboName,
		Price:           *in.Price,
		MerchantOrderId: strconv.FormatUint(pancakeOrder.ID, 10),
		Body:            *in.ComboName,
		ExpireTime:      time.Now().Add(time.Hour * 2).Unix(),
	})
	if err != nil {
		return nil, errorhandler.DefaultEntError(l.Logger, err, in)
	}
	err = l.svcCtx.DB.PancakebotOrder.UpdateOne(pancakeOrder).SetPayOrderId(payOrder.Id).Exec(l.ctx)
	if err != nil {
		return nil, errorhandler.DefaultEntError(l.Logger, err, in)
	}
	return &pay.BaseIDResp{Id: pancakeOrder.ID}, nil
}
